<template>
  <div class="calculator-container">
    <div class="calculator-wrapper">
      <div class="calculator-body">
        <!-- 左侧：输入区域 -->
        <div class="input-section">
          <div class="card upload-card">
            <div class="card-title">
              <i class="el-icon-upload"></i>
              <span>数据导入</span>
            </div>
            <el-upload
              ref="uploadRef"
              class="upload-box"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              accept=".csv"
              :multiple="false"
              :on-exceed="handleExceed"
              drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">上传CSV文件后将自动计算收益</div>
              </template>
            </el-upload>
            <div v-if="fileName" class="file-name">
              <i class="el-icon-document"></i>
              <span>{{ fileName }}</span>
            </div>
          </div>

          <div class="card settings-card">
            <div class="card-title">
              <i class="el-icon-setting"></i>
              <span>计算参数</span>
            </div>
            
            <div class="setting-item">
              <div class="setting-label">时间范围</div>
              <div class="setting-control date-control">
                <div v-if="autoDateRange.length === 2" class="date-range-container">
                  <div class="date-range-box">
                    <div class="date-range-label">始:</div>
                    <div class="date-range-value">
                      <div class="date-value-date">{{ formatDate(autoDateRange[0]) }}</div>
                      <div class="date-value-time">{{ formatTime(autoDateRange[0]) }}</div>
                    </div>
                  </div>
                  <div class="date-range-separator"></div>
                  <div class="date-range-box">
                    <div class="date-range-label">末:</div>
                    <div class="date-range-value">
                      <div class="date-value-date">{{ formatDate(autoDateRange[1]) }}</div>
                      <div class="date-value-time">{{ formatTime(autoDateRange[1]) }}</div>
                    </div>
                  </div>
                </div>
                <div v-else class="no-date-range">
                  <i class="el-icon-time"></i>
                  <span>上传CSV文件后自动获取时间范围</span>
                </div>
              </div>
            </div>

            <div class="setting-item">
              <div class="setting-label">计算参数</div>
              <div class="setting-control params-row">
                <div class="param-item">
                  <div class="param-label">倍数系数</div>
                  <el-input-number 
                    v-model="multiplier" 
                    :min="0.1" 
                    :max="1.0" 
                    :step="0.1" 
                    :precision="1"
                    @change="handleMultiplierChange"
                    placeholder="倍数系数"
                    style="width: 100%"
                  ></el-input-number>
                </div>
                <div class="param-item">
                  <div class="param-label">汇率</div>
                  <el-input-number 
                    v-model="exchangeRate" 
                    :min="0.01" 
                    :max="100" 
                    :step="0.01" 
                    :precision="2"
                    @change="handleExchangeRateChange"
                    placeholder="请输入汇率"
                    style="width: 100%"
                  ></el-input-number>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：结果区域 -->
        <div class="result-section">
          <div class="card result-card">
            <div class="card-title">
              <i class="el-icon-pie-chart"></i>
              <span>计算结果</span>
            </div>
            
            <div v-if="calculationResult" class="calculation-result">
              <!-- 截图区域，添加ref以便获取DOM元素 -->
              <div ref="resultArea" class="result-area">
                <!-- 顶部结果摘要 -->
                <div class="result-summary">
                  <div class="summary-item total-profit">
                    <div class="summary-label">总利润</div>
                    <div class="summary-value">{{ calculationResult.totalProfit.toFixed(2) }}</div>
                  </div>
                  <div class="summary-item total-commission">
                    <div class="summary-label">手续费</div>
                    <div class="summary-value">{{ calculationResult.totalCommission.toFixed(2) }}</div>
                  </div>
                  <div class="summary-item total-swap">
                    <div class="summary-label">库存费</div>
                    <div class="summary-value">{{ calculationResult.totalSwap.toFixed(2) }}</div>
                  </div>
                  <div class="summary-item final-result">
                    <div class="summary-label">结果</div>
                    <div class="summary-value highlight">{{ calculationResult.finalResult.toFixed(2) }}</div>
                  </div>
                </div>

                <!-- 计算公式 -->
                <div class="result-formula">
                  <div class="formula-title">计算公式</div>
                  <div class="formula-content">
                    <div class="formula-text">(总利润 + 手续费 + 库存费) × 倍数 × 汇率 = 结果</div>
                    <div class="formula-detail">
                      <div class="formula-line">
                        ({{ calculationResult.totalProfit.toFixed(2) }} + {{ calculationResult.totalCommission < 0 ? '(' + calculationResult.totalCommission.toFixed(2) + ')' : calculationResult.totalCommission.toFixed(2) }} + {{ calculationResult.totalSwap < 0 ? '(' + calculationResult.totalSwap.toFixed(2) + ')' : calculationResult.totalSwap.toFixed(2) }}) × {{ multiplier }} × {{ exchangeRate }} = {{ calculationResult.finalResult.toFixed(2) }}
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 时间范围信息 -->
                <div class="result-meta">
                  <div class="meta-item">
                    <span>时间范围: {{ formatDateTime(calculationResult.startDate) }} 至 {{ formatDateTime(calculationResult.endDate) }}</span>
                  </div>
                  <div class="meta-item">
                    <span>数据条数: {{ calculationResult.recordCount }}</span>
                  </div>
                  <div class="meta-item">
                    <span>汇率: {{ calculationResult.exchangeRate }}</span>
                  </div>
                </div>
              </div>

              <div class="copy-button-container">
                <button class="copy-button" @click="copyResultAsImage">
                  复制结果
                </button>
              </div>
            </div>
            <div v-else class="empty-result">
              <!-- 空状态的结果区域，保持左右结构 -->
              <div class="empty-result-content">
                <div class="empty-result-placeholder">
                  <div class="empty-summary">
                    <div class="empty-item"></div>
                    <div class="empty-item"></div>
                    <div class="empty-item"></div>
                  </div>
                  <div class="empty-formula"></div>
                  <div class="empty-meta"></div>
                </div>
                <div class="empty-result-overlay">
                  <i class="el-icon-data-analysis"></i>
                  <p>请上传CSV文件，系统将自动计算收益</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import Papa from 'papaparse'
import html2canvas from 'html2canvas'

// 状态变量
const fileName = ref('')
const fileData = ref(null)
const autoDateRange = ref([])
const multiplier = ref(0.3)
const exchangeRate = ref(7.1) // 默认汇率为7.1（美元兑人民币）
const calculationResult = ref(null)
const resultArea = ref(null) // 引用计算结果区域DOM元素
const fileList = ref([]) // 添加fileList状态变量

// 防止重复点击状态
const isCapturing = ref(false)

// 处理上传前的操作，清空之前的文件列表
const beforeUpload = (file) => {
  // 清空之前的文件列表
  fileList.value = []
  // 清空之前的计算结果和数据
  fileData.value = null
  calculationResult.value = null
  autoDateRange.value = []
  return true
}

// 处理文件移除
const handleRemove = () => {
  fileList.value = []
  fileName.value = ''
  fileData.value = null
  calculationResult.value = null
  autoDateRange.value = []
}

// 处理超出文件数量限制
const handleExceed = (files) => {
  // 当文件数量超过限制时，自动替换
  fileList.value = []
  const file = files[0]
  
  // 直接使用原始文件对象
  if (file) {
    handleFileChange({ raw: file, name: file.name })
    
    ElMessage({
      message: '已自动替换为新文件',
      type: 'success',
      duration: 2000
    })
  }
}

// 处理文件上传
const handleFileChange = (file) => {
  if (file && file.raw) {
    // 获取文件名
    const currentFileName = file.name || (file.raw ? file.raw.name : '未知文件')
    
    // 清空之前的文件列表和数据，确保只保留最新上传的文件
    fileList.value = []
    // 强制清除旧文件
    setTimeout(() => {
      fileList.value = [file]
      // 清除之前的其他文件
      fileData.value = null
      calculationResult.value = null
      autoDateRange.value = []
      fileName.value = currentFileName
      
      // 读取新文件
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const result = Papa.parse(e.target.result, {
            header: true,
            skipEmptyLines: true
          })
          fileData.value = result.data
          
          // 自动获取时间区间并计算
          if (fileData.value && fileData.value.length > 0) {
            useAutoDateRange(true) // 传递参数表示是从文件上传后调用的
          }
        } catch (error) {
          ElMessage({
            message: '文件解析失败',
            type: 'error',
            duration: 2000
          })
          // 文件解析失败
        }
      }
      reader.readAsText(file.raw)
    }, 0)
  }
}

// 处理倍数变化
const handleMultiplierChange = () => {
  if (fileData.value && fileData.value.length > 0 && autoDateRange.value.length === 2) {
    calculate(false) // 传递参数表示不显示成功消息
  }
}

// 处理汇率变化
const handleExchangeRateChange = () => {
  if (fileData.value && fileData.value.length > 0 && autoDateRange.value.length === 2) {
    calculate(false) // 传递参数表示不显示成功消息
  }
}

// 自动获取时间区间
const useAutoDateRange = (fromFileUpload = false) => {
  if (!fileData.value || fileData.value.length === 0) {
    ElMessage({
      message: '请先上传CSV文件',
      type: 'warning',
      duration: 2000
    })
    return false
  }

  try {
    // 确保数据按照closing_time_utc排序
    const sortedData = [...fileData.value].sort((a, b) => {
      const dateA = new Date(a.closing_time_utc || 0)
      const dateB = new Date(b.closing_time_utc || 0)
      return dateA - dateB
    })

    // 获取第一条和最后一条记录的时间
    const firstRecord = sortedData[0]
    const lastRecord = sortedData[sortedData.length - 1]

    if (!firstRecord.closing_time_utc || !lastRecord.closing_time_utc) {
      ElMessage({
        message: 'CSV文件中缺少closing_time_utc字段',
        type: 'warning',
        duration: 2000
      })
      return false
    }

    autoDateRange.value = [firstRecord.closing_time_utc, lastRecord.closing_time_utc]
    
    // 自动计算收益
    const calculateSuccess = calculate(fromFileUpload)
    
    // 只有当不是从文件上传调用且计算成功时才显示成功消息
    if (!fromFileUpload && calculateSuccess) {
      ElMessage({
        message: '已自动获取时间区间',
        type: 'success',
        duration: 2000
      })
    }
    
    return calculateSuccess
  } catch (error) {
    ElMessage({
      message: '获取时间区间失败',
      type: 'error',
      duration: 2000
    })
    console.error('获取时间区间错误:', error)
    return false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN');
}

// 格式化日期（仅显示年/月/日）
const formatDate = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
}

// 格式化时间（仅显示时:分:秒）
const formatTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}

// 计算收益
const calculate = (fromFileUpload = false) => {
  if (!fileData.value || fileData.value.length === 0) {
    ElMessage({
      message: '请先上传CSV文件',
      type: 'warning',
      duration: 2000
    })
    return false
  }

  if (!autoDateRange.value || autoDateRange.value.length !== 2) {
    ElMessage({
      message: '请先获取自动时间区间',
      type: 'warning',
      duration: 2000
    })
    return false
  }

  try {
    const startDate = new Date(autoDateRange.value[0])
    const endDate = new Date(autoDateRange.value[1])
    
    // 过滤日期范围内的数据，使用closing_time_utc字段
    const filteredData = fileData.value.filter(row => {
      if (!row.closing_time_utc) return false
      const rowDate = new Date(row.closing_time_utc)
      return rowDate >= startDate && rowDate <= endDate
    })

    if (filteredData.length === 0) {
      ElMessage({
        message: '所选日期范围内没有数据',
        type: 'warning',
        duration: 2000
      })
      return false
    }

    // 计算总利润、总交易手续费和总库存费
    let totalProfit = 0
    let totalCommission = 0
    let totalSwap = 0
    
    filteredData.forEach(row => {
      const profit = parseFloat(row.profit_usd || 0)
      const commission = parseFloat(row.commission_usd || 0)
      const swap = parseFloat(row.swap_usd || 0)
      
      if (!isNaN(profit)) {
        totalProfit += profit
      }
      
      if (!isNaN(commission)) {
        totalCommission += commission
      }
      
      if (!isNaN(swap)) {
        totalSwap += swap
      }
    })
    
    // 计算最终结果：(总利润 + 总交易手续费 + 总库存费) × 倍数 × 汇率
    const finalResult = (totalProfit + totalCommission + totalSwap) * multiplier.value * exchangeRate.value
    
    // 获取时间范围内的第一条和最后一条记录的时间
    // 确保按时间排序，以便获取正确的开始和结束时间
    const sortedFilteredData = [...filteredData].sort((a, b) => {
      const dateA = new Date(a.closing_time_utc || 0)
      const dateB = new Date(b.closing_time_utc || 0)
      return dateA - dateB
    })
    
    const firstRecord = sortedFilteredData[0]
    const lastRecord = sortedFilteredData[sortedFilteredData.length - 1]
    
    calculationResult.value = {
      totalProfit,
      totalCommission,
      totalSwap,
      finalResult,
      recordCount: filteredData.length,
      startDate: firstRecord.closing_time_utc,
      endDate: lastRecord.closing_time_utc,
      exchangeRate: exchangeRate.value
    }
    
    // 如果是从文件上传流程调用，显示"读取成功"消息
    if (fromFileUpload) {
      ElMessage({
        message: '读取成功',
        type: 'success',
        duration: 2000
      })
    }
    
    return true
  } catch (error) {
    ElMessage({
      message: '计算过程中出错',
      type: 'error',
      duration: 2000
    })
    console.error('计算错误:', error)
    return false
  }
}

  // 将结果区域截图并复制到剪贴板
const copyResultAsImage = async () => {
  if (!calculationResult.value || !resultArea.value) {
    ElMessage({
      message: '没有计算结果可复制',
      type: 'warning',
      duration: 2000
    })
    return
  }

  // 防止重复点击
  if (isCapturing.value) return
  isCapturing.value = true

  try {
    // 获取右侧区域的宽度
    const resultSectionWidth = document.querySelector('.result-section')?.clientWidth || 500
    
    // 创建一个固定样式的结果展示区域
    const resultDisplay = document.createElement('div')
    
    // 设置基本样式，宽度与右侧区域一致
    Object.assign(resultDisplay.style, {
      width: `${resultSectionWidth - 30}px`, // 减去padding
      padding: '15px',
      backgroundColor: '#fff',
      borderRadius: '8px',
      boxShadow: '0 2px 10px 0 rgba(0, 0, 0, 0.1)',
      fontFamily: "'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif",
      color: '#303133'
    })
    
    // 创建顶部结果摘要
    const summaryDiv = document.createElement('div')
    summaryDiv.style.cssText = 'display: flex; justify-content: space-between; margin-bottom: 12px;'
    
    // 总利润
    const profitDiv = document.createElement('div')
    profitDiv.style.cssText = 'flex: 1; padding: 10px; border-radius: 6px; text-align: center; background-color: #e1f3d8; color: #67c23a; box-shadow: 0 2px 8px rgba(103, 194, 58, 0.15);'
    
    const profitLabel = document.createElement('div')
    profitLabel.style.cssText = 'font-size: 13px; margin-bottom: 6px;'
    profitLabel.textContent = '总利润'
    
    const profitValue = document.createElement('div')
    profitValue.style.cssText = 'font-size: 18px; font-weight: 600;'
    profitValue.textContent = calculationResult.value.totalProfit.toFixed(2)
    
    profitDiv.appendChild(profitLabel)
    profitDiv.appendChild(profitValue)
    
    // 手续费
    const commissionDiv = document.createElement('div')
    commissionDiv.style.cssText = 'flex: 1; padding: 10px; border-radius: 6px; text-align: center; background-color: #f2f6fc; color: #5c6b8e; box-shadow: 0 2px 8px rgba(92, 107, 142, 0.15); margin: 0 8px;'
    
    const commissionLabel = document.createElement('div')
    commissionLabel.style.cssText = 'font-size: 13px; margin-bottom: 6px;'
    commissionLabel.textContent = '手续费'
    
    const commissionValue = document.createElement('div')
    commissionValue.style.cssText = 'font-size: 18px; font-weight: 600;'
    commissionValue.textContent = calculationResult.value.totalCommission.toFixed(2)
    
    commissionDiv.appendChild(commissionLabel)
    commissionDiv.appendChild(commissionValue)
    
    // 库存费
    const swapDiv = document.createElement('div')
    swapDiv.style.cssText = 'flex: 1; padding: 10px; border-radius: 6px; text-align: center; background-color: #fdf6ec; color: #e6a23c; box-shadow: 0 2px 8px rgba(230, 162, 60, 0.15); margin: 0 8px;'
    
    const swapLabel = document.createElement('div')
    swapLabel.style.cssText = 'font-size: 13px; margin-bottom: 6px;'
    swapLabel.textContent = '库存费'
    
    const swapValue = document.createElement('div')
    swapValue.style.cssText = 'font-size: 18px; font-weight: 600;'
    swapValue.textContent = calculationResult.value.totalSwap.toFixed(2)
    
    swapDiv.appendChild(swapLabel)
    swapDiv.appendChild(swapValue)
    
    // 结果
    const resultDiv = document.createElement('div')
    resultDiv.style.cssText = 'flex: 1; padding: 10px; border-radius: 6px; text-align: center; background-color: #d9ecff; color: #409eff; box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);'
    
    const resultLabel = document.createElement('div')
    resultLabel.style.cssText = 'font-size: 13px; margin-bottom: 6px;'
    resultLabel.textContent = '结果'
    
    const resultValue = document.createElement('div')
    resultValue.style.cssText = 'font-size: 22px; font-weight: 600;'
    resultValue.textContent = calculationResult.value.finalResult.toFixed(2)
    
    resultDiv.appendChild(resultLabel)
    resultDiv.appendChild(resultValue)
    
    // 将四个部分添加到摘要区域
    summaryDiv.appendChild(profitDiv)
    summaryDiv.appendChild(commissionDiv)
    summaryDiv.appendChild(swapDiv)
    summaryDiv.appendChild(resultDiv)
    
    // 创建计算公式区域
    const formulaDiv = document.createElement('div')
    formulaDiv.style.cssText = 'background-color: #f8f8f8; padding: 12px; border-radius: 6px; margin: 12px 0;'
    
    const formulaTitle = document.createElement('div')
    formulaTitle.style.cssText = 'font-weight: 600; margin-bottom: 8px; color: #303133; font-size: 14px;'
    formulaTitle.textContent = '计算公式'
    
    const formulaContent = document.createElement('div')
    
    const formulaText = document.createElement('div')
    formulaText.style.cssText = 'font-size: 14px; color: #606266; margin-bottom: 4px;'
    formulaText.textContent = '(总利润 + 手续费 + 库存费) × 倍数 × 汇率 = 结果'
    
    const formulaDetail = document.createElement('div')
    formulaDetail.style.cssText = 'position: relative; padding-left: 12px;'
    
    // 创建左侧蓝色边框
    const borderDiv = document.createElement('div')
    borderDiv.style.cssText = 'position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background-color: #409eff; border-radius: 2px;'
    formulaDetail.appendChild(borderDiv)
    
    const formulaLine = document.createElement('div')
    formulaLine.style.cssText = 'font-family: monospace; background-color: white; padding: 8px; border-radius: 4px; color: #606266; font-size: 13px;'
    
    // 处理负数显示，添加括号
    const commissionStr = calculationResult.value.totalCommission < 0 
      ? `(${calculationResult.value.totalCommission.toFixed(2)})`
      : calculationResult.value.totalCommission.toFixed(2)
      
    const swapStr = calculationResult.value.totalSwap < 0
      ? `(${calculationResult.value.totalSwap.toFixed(2)})`
      : calculationResult.value.totalSwap.toFixed(2)
      
    formulaLine.textContent = `(${calculationResult.value.totalProfit.toFixed(2)} + ${commissionStr} + ${swapStr}) × ${multiplier.value} × ${exchangeRate.value} = ${calculationResult.value.finalResult.toFixed(2)}`
    
    formulaDetail.appendChild(formulaLine)
    
    formulaContent.appendChild(formulaText)
    formulaContent.appendChild(formulaDetail)
    
    formulaDiv.appendChild(formulaTitle)
    formulaDiv.appendChild(formulaContent)
    
    // 创建元数据区域
    const metaDiv = document.createElement('div')
    metaDiv.style.cssText = 'display: flex; flex-direction: column; gap: 6px; color: #606266; font-size: 13px; padding: 8px 0;'
    
    const timeRangeDiv = document.createElement('div')
    timeRangeDiv.textContent = `时间范围: ${formatDateTime(calculationResult.value.startDate)} 至 ${formatDateTime(calculationResult.value.endDate)}`
    
    const recordCountDiv = document.createElement('div')
    recordCountDiv.textContent = `数据条数: ${calculationResult.value.recordCount}`
    
    const exchangeRateDiv = document.createElement('div')
    exchangeRateDiv.textContent = `汇率: ${calculationResult.value.exchangeRate}`
    
    metaDiv.appendChild(timeRangeDiv)
    metaDiv.appendChild(recordCountDiv)
    metaDiv.appendChild(exchangeRateDiv)
    
    // 将所有部分添加到主容器
    resultDisplay.appendChild(summaryDiv)
    resultDisplay.appendChild(formulaDiv)
    resultDisplay.appendChild(metaDiv)
    
    // 将容器添加到文档中（但不可见）
    resultDisplay.style.position = 'absolute'
    resultDisplay.style.left = '-9999px'
    resultDisplay.style.top = '-9999px'
    document.body.appendChild(resultDisplay)
    
    // 等待一小段时间确保渲染完成
    await new Promise(resolve => setTimeout(resolve, 200))
    
    // 使用html2canvas生成截图
    const canvas = await html2canvas(resultDisplay, {
      backgroundColor: '#fff',
      scale: 2, // 提高清晰度
      logging: false,
      useCORS: true,
      allowTaint: true
    })
    
    // 移除临时元素
    document.body.removeChild(resultDisplay)
    
    // 获取图片数据
    const imgData = canvas.toDataURL('image/png')
    
    try {
      // 尝试复制到剪贴板
      const blob = await (await fetch(imgData)).blob()
      const data = [new ClipboardItem({ 'image/png': blob })]
      await navigator.clipboard.write(data)
      
      ElMessage({
        message: '截图已复制到剪贴板',
        type: 'success',
        duration: 2000
      })
    } catch (error) {
      console.error('复制到剪贴板失败:', error)
      
      // 如果复制失败，创建下载链接
      const link = document.createElement('a')
      link.download = '计算结果.png'
      link.href = imgData
      link.click()
      
      ElMessage({
        message: '无法复制到剪贴板，已下载截图',
        type: 'warning',
        duration: 3000
      })
    } finally {
      isCapturing.value = false
    }
  } catch (error) {
    console.error('生成截图失败:', error)
    ElMessage({
      message: '生成截图失败',
      type: 'error',
      duration: 2000
    })
    
    // 如果截图失败，回退到文本复制
    copyResultAsText()
    isCapturing.value = false
  }
}

// 将结果复制为文本（作为备用方案）
const copyResultAsText = () => {
  if (!calculationResult.value) return
  
  const result = calculationResult.value
  let textToCopy = `时间范围: ${formatDateTime(result.startDate)} 至 ${formatDateTime(result.endDate)}\n`
  textToCopy += `数据条数: ${result.recordCount}\n`
  textToCopy += `计算公式: (总利润 + 手续费 + 库存费) × 倍数 × 汇率 = 结果\n`
  
  // 处理负数显示，添加括号
  const commissionStr = result.totalCommission < 0 
    ? `(${result.totalCommission.toFixed(2)})`
    : result.totalCommission.toFixed(2)
    
  const swapStr = result.totalSwap < 0
    ? `(${result.totalSwap.toFixed(2)})`
    : result.totalSwap.toFixed(2)
    
  textToCopy += `(${result.totalProfit.toFixed(2)} + ${commissionStr} + ${swapStr}) × ${multiplier.value} × ${result.exchangeRate} = ${result.finalResult.toFixed(2)}\n`
  textToCopy += `结果: ${result.finalResult.toFixed(2)}`

  navigator.clipboard.writeText(textToCopy)
    .then(() => ElMessage({
      message: '结果已以文本形式复制到剪贴板',
      type: 'success',
      duration: 2000
    }))
    .catch(() => ElMessage({
      message: '复制失败',
      type: 'error',
      duration: 2000
    }))
}
</script>

<style scoped>
.calculator-container {
  min-height: 100vh;
  height: 100vh;
  width: 100vw;
  background: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  margin: 0;
  font-family: 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.calculator-wrapper {
  width: 100%;
  max-width: 100%;
  height: 100vh;
  background-color: #ffffff;
  border-radius: 0;
  box-shadow: none;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

.calculator-header {
  padding: 20px;
  text-align: center;
  background: linear-gradient(to right, #3a7bd5, #00d2ff);
  color: white;
}

.calculator-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.subtitle {
  margin-top: 6px;
  font-size: 14px;
  opacity: 0.9;
}

.calculator-body {
  display: flex;
  padding: 15px;
  gap: 15px;
  flex: 1;
  overflow: hidden;
}

@media (max-width: 900px) {
  .calculator-body {
    flex-direction: column;
  }
}

.input-section, .result-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: hidden; /* 防止区域出现滚动条 */
}

.card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  padding: 15px;
  height: 100%;
}

/* 调整上传卡片和设置卡片的高度比例 */
.upload-card {
  flex: 0.4;
}

.settings-card {
  flex: 0.6;
}

/* 确保结果卡片占满整个高度但不溢出 */
.result-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止结果卡片出现滚动条 */
}

.card-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.card-title i {
  margin-right: 8px;
  font-size: 20px;
  color: #3a7bd5;
}

.upload-box {
  width: 100%;
}

.file-name {
  margin-top: 15px;
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  color: #67c23a;
}

.file-name i {
  margin-right: 8px;
}

.setting-item {
  margin-bottom: 15px;
}

.setting-label {
  font-weight: 500;
  margin-bottom: 6px;
  color: #606266;
}

.setting-control {
  width: 100%;
}

.date-control {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 日期范围样式 */
.date-range-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 4px;
  border: 1px solid #eaeaea;
}

.date-range-box {
  flex: 1;
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 5px;
  padding: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.date-range-label {
  font-weight: 600;
  color: #606266;
  margin-right: 8px;
  min-width: 25px;
  text-align: center;
}

.date-range-value {
  flex: 1;
}

.date-value-date {
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
  font-size: 13px;
}

.date-value-time {
  font-size: 12px;
  color: #909399;
}

.date-range-separator {
  width: 20px;
  height: 2px;
  background-color: #dcdfe6;
  margin: 0 10px;
}

.no-date-range {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  background-color: #f4f4f5;
  border-radius: 6px;
  color: #909399;
  font-size: 13px;
}

.no-date-range i {
  margin-right: 8px;
  font-size: 18px;
}

.calculation-result {
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: auto; /* 只在结果内容区域允许滚动 */
  flex: 1; /* 占满剩余空间 */
}

/* 结果区域样式 - 用于截图 */
.result-area {
  display: flex;
  flex-direction: column;
  gap: 12px;
  border-radius: 8px;
  overflow: visible; /* 允许内容显示 */
}

.result-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0;
}

.summary-item {
  flex: 1;
  padding: 12px;
  border-radius: 6px;
  text-align: center;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.summary-item.total-profit {
  background-color: #e1f3d8;
  color: #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.15);
}

.summary-item.total-commission {
  background-color: #f2f6fc;
  color: #5c6b8e;
  margin: 0 5px;
  box-shadow: 0 2px 8px rgba(92, 107, 142, 0.15);
}

.summary-item.total-swap {
  background-color: #fdf6ec;
  color: #e6a23c;
  margin: 0 5px;
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.15);
}

.summary-item.final-result {
  background-color: #d9ecff;
  color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.summary-label {
  font-size: 13px;
  margin-bottom: 6px;
}

.summary-value {
  font-size: 18px;
  font-weight: 600;
}

.summary-value.highlight {
  font-size: 22px;
  color: #409eff;
}

.result-formula {
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 6px;
}

.formula-title {
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
  font-size: 14px;
}

.formula-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.formula-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.formula-detail {
  position: relative;
  padding-left: 15px;
}

.formula-detail::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: #409eff;
  border-radius: 2px;
}

.formula-line {
  font-family: monospace;
  background-color: white;
  padding: 8px;
  border-radius: 4px;
  color: #606266;
  font-size: 13px;
}

.result-meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  color: #606266;
  font-size: 13px;
  padding: 8px 0;
}

.meta-item {
  display: flex;
  align-items: center;
}

/* 复制按钮样式 */
.copy-button-container {
  display: flex;
  justify-content: center;
  margin-top: 12px;
}

.copy-button {
  background-color: #67c23a;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  box-shadow: 0 2px 6px rgba(103, 194, 58, 0.3);
}

.copy-button:hover {
  background-color: #5daf34;
}

.copy-button:active {
  transform: translateY(1px);
}

/* 空状态结果区域样式 */
.empty-result {
  position: relative;
  height: 100%;
  min-height: 200px; /* 减小最小高度 */
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止空状态出现滚动条 */
}

.empty-result-content {
  position: relative;
  height: 100%;
  width: 100%;
}

.empty-result-placeholder {
  opacity: 0.1;
  padding: 12px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.empty-summary {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.empty-item {
  flex: 1;
  height: 70px;
  background-color: #e0e0e0;
  border-radius: 6px;
}

.empty-formula {
  height: 100px;
  background-color: #e0e0e0;
  border-radius: 6px;
  margin: 8px 0;
}

.empty-meta {
  height: 60px;
  background-color: #e0e0e0;
  border-radius: 6px;
}

.empty-result-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.empty-result-overlay i {
  font-size: 40px;
  margin-bottom: 12px;
  opacity: 0.5;
  color: #409eff;
}

.empty-result-overlay p {
  font-size: 14px;
  text-align: center;
  max-width: 80%;
  line-height: 1.5;
}

/* 移除旧的空状态样式 */
.no-result {
  display: none;
}

.params-row {
  display: flex;
  gap: 15px;
}

.param-item {
  flex: 1;
}

.param-label {
  font-size: 13px;
  margin-bottom: 5px;
  color: #606266;
}
</style> 